package com.bdqn.t330.ch12.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bdqn.t330.ch12.entity.Page;
import com.bdqn.t330.ch12.entity.Role;
import com.bdqn.t330.ch12.entity.SysUser;
import com.bdqn.t330.ch12.service.RoleService;
import com.bdqn.t330.ch12.service.UserService;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/user")
public class UserController {


    private Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    UserService userService;

    @Resource
    RoleService roleService;

    //public String add();
    //public String delete();
    //public String update();

    @RequestMapping("/userList")
    public String userList(Model model) {
        List<SysUser> userList = userService.getUserList();
        model.addAttribute("list", userList);
        return "/user/list";
    }

    @RequestMapping("/userListPage")
    public String userListPage(Model model, Integer pageIndex, Integer pageSize, String userName) {

        if (pageIndex == null) {
            pageIndex = 1;
        }
        if (pageSize == null) {
            pageSize = 5;
        }

        Page page = new Page();
        page.setCurrentPage(pageIndex);
        page.setPageSize(pageSize);

        List<SysUser> listPage = userService.getUserListPageBiz(pageIndex, pageSize, userName);
        page.setList(listPage);
        //设置总记录数的同时要计算出总页数
        page.setTotalRecord(userService.getUserListPageCount(userName));

        List<Role> roleList = roleService.roleListBiz();

        //model.addAttribute("listPage", listPage);
        //回传当前页码
        //model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("page", page);
        model.addAttribute("userName", userName);
        model.addAttribute("roleList", roleList);
        return "/user/listPage";
    }

    //如果是ajax请求的返回值需要添加@ResponseBody
    @ResponseBody
    @RequestMapping(value = "/getRoleList", produces = {"application/json;charset=UTF-8"})
    public Object getRoleList() {
        List<Role> roleList = roleService.roleListBiz();
        return JSON.toJSONString(roleList, SerializerFeature.WriteMapNullValue);
    }

    //如果是ajax请求的返回值需要添加@ResponseBody
    @ResponseBody
    @RequestMapping(value = "/getUserCodeExists", produces = {"application/json;charset=UTF-8"})
    public Object getUserCodeExists(String userCode) {
        Map<String, Object> map = new HashMap<>();
        if (userCode == null || userCode.length() < 1) {
            map.put("result", "0");
        } else {
            int count = userService.getUserCodeExistsBiz(userCode);
            map.put("result", count);
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping("/toAdd")
    public String getUserList() {
        return "/user/add";
    }

    @RequestMapping("/add")
    public String add(Model model, SysUser sysUser, MultipartFile idPic, HttpSession session, HttpServletRequest request) {
        SysUser user = (SysUser) session.getAttribute("sysUser");
        //判断用户是否已经登录
        if (user == null) {
            throw new RuntimeException("请先登录!");
        }
        //判断附件是否为空
        if (idPic != null) {
            //获得用户上传文件名称
            String userImg = idPic.getOriginalFilename();
            sysUser.setUserImg(userImg);
            //获得文件的后缀 FilenameUtils工具类需要导入commons-io jar包
            String suffix = FilenameUtils.getExtension(userImg);
            //定义一个随机数
            String uuid = UUID.randomUUID().toString();
            //定义保存到硬盘上的图片名称
            String uploadImg = uuid + "." + suffix;
            sysUser.setUploadImg(uploadImg);

            //找到上传文件的目录
            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
            //String path = "d:\\img";
            System.out.println("path:" + path);
            File targetFile = new File(path);
            //判断上传目录是否存在
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            try {
                //idPic.transferTo(new File("D:\\img","test.png"));
                idPic.transferTo(new File(targetFile, uploadImg));
            } catch (IOException e) {
                e.printStackTrace();
                return "redirect:/user/userListPage";
            }
        }
        sysUser.setCreatedBy(user.getId());
        sysUser.setCreationDate(new Date());
        int count = userService.add(sysUser);
        if (count > 0) {
            return "redirect:/user/userListPage";
        } else {
            return "/user/add";
        }
    }

    @RequestMapping("/deleteById")
    public String getUserList(Integer id) {
        int count = userService.deleteByIdBiz(id);
        if (count > 0) {
            return "redirect:/user/userListPage";
        } else {
            return "/user/add";
        }
    }

    @RequestMapping("/view")  //@RequestParam(value = "id") 可以省略
    public String view(@RequestParam(value = "id") Integer id, Model model) {
        SysUser sysUser = userService.viewBiz(id);
        model.addAttribute("sysUser", sysUser);
        return "/user/view";
    }


    //http://localhost:8080/ch12/user/find/66
    @GetMapping("/find/{id}")   //restfull风格@PathVariable(value = "id") 不能省略
    @ResponseBody
    @CrossOrigin
    public Object find1(@PathVariable(value = "id") Integer id, Model model) {
        SysUser sysUser = userService.viewBiz(id);
        //model.addAttribute("sysUser", sysUser);
        //return "/user/view";
        return sysUser;
    }

    //http://localhost:8080/ch12/user/find/66
    @PostMapping("/find/{id}")   //restfull风格@PathVariable(value = "id") 不能省略
    @ResponseBody
    public String find2(@PathVariable(value = "id") Integer id, Model model) {
        SysUser sysUser = userService.viewBiz(id);
        //model.addAttribute("sysUser", sysUser);
        //return "/user/view";
        return JSON.toJSONString(sysUser);
    }
}
